<template>
  <div>
    <h1>天气应用</h1>
    <p v-if="loading">正在加载天气数据...</p>
    <div v-else>
      <h2>{{ cityName }}</h2>
      <p>{{ currentWeather.temperature }}°C</p>
      <p>{{ currentWeather.description }}</p>
      <ul class="forecast-list">
        <li v-for="forecast in forecastData" :key="forecast.date">
          <p>{{ forecast.date }}</p>
          <p>{{ forecast.temperature }}°C</p>
          <p>{{ forecast.description }}</p>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data () {
    return {
      cityName: '',
      currentWeather: {},
      forecastData: [],
      loading: true
    };
  },
  async created () {
    const apiKey = 'd9dc5890e363a69f6fc5f56588125f7d';
    const city = 'xian';
    try {
      const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`);
      this.cityName = response.data.name;
      this.currentWeather = {
        temperature: response.data.main.temp - 273.15,
        description: response.data.weather[0].description
      };
      const forecastResponse = await axios.get(`https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apiKey}`);
      this.forecastData = forecastResponse.data.list.map(item => ({
        date: item.dt_txt,
        temperature: item.main.temp - 273.15,
        description: item.weather[0].description
      }));
      this.loading = false;
    } catch (error) {
      console.error('获取天气数据失败：', error);
      this.loading = false;
    }
  }
};
</script>
<style scoped>
.forecast-list {
  list-style: none;
  margin: 0;
  padding: 0;
  background-color: #fff; /* 白色背景板 */
  border-radius: 8px; /* 圆角 */
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1); /* 添加阴影 */
}

.forecast-list li {
  padding: 10px 15px; /* 内边距 */
  border-bottom: 1px solid #eee; /* 分割线 */
  display: flex;
  align-items: center;
}

.forecast-list li:last-child {
  border-bottom: none; /* 移除最后一个元素的分割线 */
}

.forecast-list li p {
  margin: 0 10px 0 0;
}

.loading {
  text-align: center;
  font-size: 18px;
  color: #777;
}
</style>